package com.deeper.customview.ui.c2.exercise.c02e02;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.Nullable;

public class RuleView extends View {
    private Paint rulerBoardPaint;
    private Paint rulerTickPaint;

    public RuleView(Context context) {
        super(context);
    }


    public RuleView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        rulerBoardPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        rulerBoardPaint.setStyle(Paint.Style.FILL_AND_STROKE);
        rulerBoardPaint.setStrokeWidth(1);
        rulerBoardPaint.setColor(Color.GRAY);

        rulerTickPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        rulerTickPaint.setStyle(Paint.Style.STROKE);
        rulerTickPaint.setStrokeWidth(1);
        rulerTickPaint.setColor(Color.BLACK);
    }


    public RuleView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }


    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //获取宽高
        int width = getMeasuredWidth();
        int height = getMeasuredHeight();

        int horizontal_margin = 20;
        int vertical_margin = 300;
        int ruleWidth = width - horizontal_margin * 2;
        int ruleHeight = 300;

        canvas.saveLayer(horizontal_margin, vertical_margin, ruleWidth + horizontal_margin, ruleHeight + vertical_margin, null);

        //绘制边框
        canvas.drawRoundRect(horizontal_margin, vertical_margin, ruleWidth + horizontal_margin, ruleHeight + vertical_margin, 10, 10, rulerBoardPaint);

        //绘制刻度
        canvas.save();
        canvas.translate(horizontal_margin + 50, 0);
        for (int i = 0; i < 90; i++) {
            if (i % 5 == 0) {
                if (i % 10 == 0) {
                    //长刻度
                    canvas.drawLine(0, (float) (vertical_margin + 0.2 * ruleHeight), 0, vertical_margin + ruleHeight, rulerTickPaint);

                    rulerTickPaint.setTextSize(20);
                    if (i == 0) {
                        canvas.drawText("0 cm", 0, (float) (vertical_margin + 0.2 * ruleHeight - 10), rulerTickPaint);
                    } else {
                        canvas.drawText(String.valueOf(i / 10), 0, (float) (vertical_margin + 0.2 * ruleHeight - 10), rulerTickPaint);
                    }
                } else {
                    //中刻度
                    canvas.drawLine(0, (float) (vertical_margin + 0.5 * ruleHeight), 0, vertical_margin + ruleHeight, rulerTickPaint);
                }
            } else {
                //短刻度
                canvas.drawLine(0, (float) (vertical_margin + 0.7 * ruleHeight), 0, vertical_margin + ruleHeight, rulerTickPaint);
            }
            canvas.translate(10, 0);
        }
        canvas.restore();
    }
}
